﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace KZ400B.Controls
{
    public delegate void UserSettingSave();
    public delegate void UserSettingClose();
    /// <summary>
    /// UserParameterSetting.xaml 的交互逻辑
    /// </summary>
    public partial class UserParameterSetting : UserControl
    {
        public event UserSettingClose OnClose;
        public UserParameterSetting()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            txtPositionDisplayDecimals.Text = MySetting.PositionDisplayDecimals.ToString();
            txtOSDisplayDecimals.Text = MySetting.OSDisplayDecimals.ToString();
            txtRunPWMLimit.Text = MySetting.RunPWMLimit.ToString();
            txtToZeroPWMLimit.Text = MySetting.ToZeroPWMLimit.ToString();
        }

        private int getIntValueFromText(string tag,TextBox control)
        {
            int iv = 0;
            if (!string.IsNullOrEmpty(control.Text))
            {
                if (int.TryParse(control.Text, out iv))
                {
                    return iv;
                }
            }
            throw new Exception(string.Format("{0} 中:请输入数字",tag));
            
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MySetting.PositionDisplayDecimals = getIntValueFromText(
                    labPositionDisplayDecimals.Content.ToString()
                    , txtPositionDisplayDecimals
                    );

                MySetting.OSDisplayDecimals = getIntValueFromText(
                labOSDisplayDecimals.Content.ToString()
                , txtOSDisplayDecimals
                );

                MySetting.RunPWMLimit = getIntValueFromText(
                labRunPWMLimit.Content.ToString()
                , txtRunPWMLimit
                );

                        MySetting.ToZeroPWMLimit = getIntValueFromText(
                labToZeroPWMLimit.Content.ToString()
                , txtToZeroPWMLimit
                );

                MySetting.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            if (OnClose != null)
            {
                OnClose();
            }
        }


    }
}
